import { saveWorkFlow, queryWorkFlow } from '../services';

const hasCondition = (state, formId, needIndex = false) => {
    const index = state.findIndex(d => d.formId === formId);
    return needIndex ? index : index > -1;
};

// 获取所有流程数据的conditions集合
const getAllConditions = data => {
    if (!data) {
        return null;
    }
    let arr = [];

    const getCondition = node => {
        if (node?.conditionNodes) {
            node.conditionNodes.forEach(item => {
                arr = [...arr, ...item.properties.conditions];
                if (item?.conditionNodes) {
                    getCondition(item);
                }
                if (item?.childNode) {
                    getCondition(item.childNode);
                }
            });
        }
        if (node?.childNode) {
            getCondition(node.childNode);
        }
    };
    getCondition(data);
    return arr;
};

export default {
    namespace: 'workFlowModel',
    state: {
        processConditions: [], // processConditions 用于传递流程图需要的条件
        formItemList: [], // 流程节点表单权限控制——组件列表
        // 基础设置
        basicData: {
            // processKey: 'PROCESSKEY52dddd8',
            processName: '空模板',
            category: null,
            description: null,
            organizationCode: null,
            scopeGroup: { scopeField: 'company', scopeValue: [] }
        },
        processData: null, // 流程设计
        advancedData: {} // 高级设置
    },

    effects: {
        // 发布
        *updataWorkFlow({ payload }, { call }) {
            const response = yield call(saveWorkFlow, payload);
            return response;
        },
        // 拉取流程设计编辑状态
        *fetchWorkFlow({ payload, callback }, { call, put }) {
            const response = yield call(queryWorkFlow, payload);
            if (response.code === 10000) {
                const { formJson, processJson, processConfig, advancedSetting } = response.data;
                const templist = JSON.parse(formJson);
                const tempprolist = [];
                templist.forEach(item => {
                    if (item.proCondition) {
                        tempprolist.push(item);
                    }
                });
                yield put({
                    type: 'save',
                    payload: {
                        processConditions: tempprolist,
                        formItemList: templist,
                        processData: JSON.parse(processJson),
                        basicData: processConfig,
                        advancedData: advancedSetting || {}
                    }
                });
                if (callback) {
                    callback(response);
                }
            }
        }
    },
    reducers: {
        // 初始化流程数据
        initWorkFlowData(state) {
            return {
                ...state,
                processConditions: [],
                formItemList: [],
                basicData: {
                    explanation: null,
                    scopeGroup: { scopeField: 'company', scopeValue: [] }
                },
                processData: null,
                advancedData: {},
                description: null
            };
        },
        // 基础设置修改
        basicDataSave(state, { payload }) {
            return { ...state, basicData: { ...state.basicData, ...payload } };
        },
        // 流程设计修改
        processDataSave(state, { payload }) {
            return { ...state, processData: payload };
        },
        save(state, { payload }) {
            return { ...state, ...payload };
        },
        updateFormItemList(state, { payload }) {
            return { ...state, formItemList: payload };
        },
        // 添加作为条件控件
        addPCondition(state, { payload }) {
            console.log(payload, 'payloadpayloadpayloadpayload');
            const { formId } = payload;
            const newArr = state.processConditions;
            const index = hasCondition(newArr, formId, true);
            if (index > -1) {
                newArr.splice(index, 1, payload);
            } else {
                newArr.push(payload);
            }
            return { ...state, processConditions: newArr };
        },
        // 删除作为条件控件
        delPCondition(state, { payload }) {
            console.log(payload, 'delPConditiondelPConditiondelPConditiondelPConditiondelPCondition');

            const { formId } = payload;
            const newArr = state.processConditions;
            const index = hasCondition(newArr, formId, true);
            if (index > -1) {
                newArr.splice(index, 1);
            }

            return { ...state, processConditions: newArr };
        },
        // 根据传入的流程设计数据更新作为条件的控件使用属性
        updateCondition(state, { payload }) {
            const { data } = payload;
            let proArr = state.processConditions;
            const condArr = getAllConditions(data);
            // console.log('=============>condArr', condArr);

            const changeIsUsed = arr => {
                arr.map(item => {
                    const obj = item;
                    obj.isUsed = false;
                    let isHas = condArr.findIndex(subItem => subItem.formId === item.formId);

                    if (item.children && item.children.length > 0) {
                        for (let i = 0; i < item.children.length; i += 1) {
                            isHas = condArr.findIndex(tItem => tItem.formId === item.children[i].formId);
                            if (isHas > -1) {
                                break;
                            }
                        }
                        changeIsUsed(item.children);
                    }
                    if (isHas > -1) {
                        obj.isUsed = true;
                    }
                    return obj;
                });
                return arr;
            };

            proArr = changeIsUsed(proArr);

            // 更新组件列表使用属性
            let formItemListArr = state.formItemList;
            formItemListArr = changeIsUsed(formItemListArr);

            // console.log('=========>formItemListArr', formItemListArr);
            // console.log('=============>proArr', proArr);

            return { ...state, processConditions: [...proArr], formItemList: [...formItemListArr] };
        }
    },
    subscriptions: {
        setup({ dispatch, history }) {
            return history.listen(({ pathname, query }) => {
                if (pathname.includes('office/institutions/flowManageNew/formDesign') && query.id === undefined) {
                    dispatch({
                        type: 'initWorkFlowData'
                    });
                }
            });
        }
    }
};
